package com.zlyx.easy.socket.core;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.zlyx.easy.core.thread.BlockThread;
import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.core.utils.ThreadUtils;
import com.zlyx.easy.socket.core.supports.AbstractMsgHandlerFactory;
import com.zlyx.easy.socket.interfaces.IMsgHandler;

/**
 * BIO方式处理TCP消息工厂
 * 
 * @author 赵光
 * @Description: BIO方式处理TCP消息工厂
 * @date 2018年11月14日
 */
public class BioTcpMsgHandlerFactory extends AbstractMsgHandlerFactory {

	ServerSocket ss;
	Socket socket;

	public BioTcpMsgHandlerFactory(int port, float size, IMsgHandler<?> handler) throws Exception {
		super(port, size, handler);
		ss = new ServerSocket(this.PORT);
	}

	@Override
	public boolean doBlock() throws Exception {
		socket = ss.accept();
		ThreadUtils.execute(new Handler(socket));
		return true;
	}

	@Override
	public void closeServer() throws Exception {
		if (socket != null) {
			socket.close();
		}
		if (ss != null) {
			ss.close();
		}
	}

	public class Handler extends BlockThread {

		protected Socket socket;
		protected BufferedReader reader;
		protected PrintWriter writer;

		public Handler(Socket socket) throws Exception {
			this.socket = socket;
			this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			this.writer = new PrintWriter(socket.getOutputStream(), true);
		}

		@Override
		public boolean doBlock() throws Exception {
			byte[] data = new byte[BLOCK];
			int size = socket.getInputStream().read(data);
			if (size > 0) {
				byte[] res = doHandler(new String(data));
				if (ObjectUtils.isNotEmpty(res)) {
					socket.getOutputStream().write(res);
				}
			}
			return true;
		}

		@Override
		public void doFinal() throws Exception {
			reader.close();
			writer.close();
			socket.close();
		}
	}
}
